package com.etrans.web.gps.business.gis.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.etrans.egov.base.intf.ObjDriver;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.gis.domain.Track;
import com.etrans.web.gps.business.gis.service.MonitorService;
import com.etrans.web.gps.business.system.domain.SysUser;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.util.Config;
import com.etrans.web.gps.util.DateUtil;
import com.etrans.web.gps.util.grid.FlexiGridUtil;
@Controller
@RequestMapping("/gis/monitor")
public class MonitorController extends BaseController{
	private static final Logger logger = LoggerFactory.getLogger(MonitorController.class);
	@Autowired
    private MonitorService monitorService;
	@Autowired
	private Config config; //引用统一的参数配置类 
	
	/**
	 * 跳转到定位页面
	 * @Description 页面跳转
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "location.html")
	public String index(Model model){
		//#高德地图解析地址
		model.addAttribute("addressPath", config.addressPath);
		return "views/business/gis/monitor";
	}
	
	/**
	 * 定位监控树
	 * @throws Exception 
	 */
	@RequestMapping(value = "getVehicleTree.html")
	@ResponseBody
	public String allVehicleTree(HttpServletRequest request,HttpServletResponse response){	
		try {
			SysUser user = (SysUser)getSession().getAttribute(Constant.LOGIN_SESSION_NAME);
			Map<String, Object> param = new HashMap<String,Object>();
			param.put("userId", user.getId());
			param.put("area_id", user.getArea_id());
			param.put("fullID", user.getFullID());
			this.ajaxResultJsonWithGzip(request, response, monitorService.getMonitorTreeJsonResult(param));
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 业户查询车辆
	 * @throws Exception 
	 *@Description 查询结果
	 */
	@RequestMapping(value = "queryVehicleByEnt.html")
	@ResponseBody
	public Map<String, Object> queryVehicleByEnt(String paramsGrid){
		try {
			Map<String, Object> result = new HashMap<>();
			Map<String, Object> param =  FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
			List<HashMap<String,Object>> vehicles = monitorService.queryVehicleByEnt(param);
			result.put("rows", vehicles);
			return  result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 查询车辆
	 * @throws Exception 
	 */
	@RequestMapping(value = "queryVehicleByCondition.html")
	@ResponseBody
	public HashMap<String, Object> queryVehicleByCondition(String paramsGrid) throws Exception{
		SysUser user = getSysUser();
		HashMap<String, Object> result = new HashMap<>();
		HashMap<String, Object> param =  FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
		param.put("fullID", user.getFullID());
		List<HashMap<String, Object>> vehicles = monitorService.queryVehicleByCondition(param);
		result.put("rows", vehicles);
		return result;
	}
	
	/**
	 *@throws Exception 
	 * @Description 车辆上下线状态 
	 * 
	 */
	@RequestMapping(value = "queryVehicleStatus.html")
	@ResponseBody
	public List<String> queryVehicleStatus(String vehicle_no_color){
		try {
			if(vehicle_no_color != null && !"".equals(vehicle_no_color)){
				return monitorService.queryVehicleStatus(vehicle_no_color.split(","));
			}else{
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * @Description 多车实时监控页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "multiVehicleMonitor.html")
	public String multiVehicleMonitor(Model model){
		return "views/business/gis/multiVehicleMonitor";
	}
	/**
	 * @Description 实时监控
	 * @param model
	 * @param isMulti 
	 * @param commnos 通信号
	 * @return
	 */
	@RequestMapping(value = "vehicleMonitor.html")
	public String vehicleMonitor(Model model,String vehicle_no_color){
		if(vehicle_no_color != null && !"".equals(vehicle_no_color)){
			model.addAttribute("vehicle_no", vehicle_no_color.split("_")[0]);
		}
		return "views/business/gis/vehicleMonitor";
	}
	/**
	 * @Description 多车监控车辆切换列表
	 */
	@RequestMapping("queryVehicleList.html")
	@ResponseBody
	public List<HashMap<String,Object>> queryVehicleList() {
		SysUser user = getSysUser();
		
		List<HashMap<String,Object>> list=monitorService.queryVeList(user.getArea_id());
		HashMap<String, Object> map =new HashMap<>();
		map.put("text", "请选择车辆");
		map.put("id", 0);
		list.add(0, map);
		return list;
	}
	/**
	 * @Description 订阅车辆
	 * @param vehicle_no_color 车牌号_车牌颜色
	 * @throws Exception 
	 */
	@RequestMapping("subScribe.html")
	@ResponseBody
	public Map<String,Object> subScribe(String vehicle_no_color,String v){
		try {
			Map<String,Object> result = new HashMap<>();
			if(vehicle_no_color == null || "".equals(vehicle_no_color)){
				return null;
			}
			String no_color = URLDecoder.decode(vehicle_no_color, "utf-8");
			List<Track> trackList = monitorService.getSubScribe(no_color.split(","));
			result.put("v", v);
			result.put("data", trackList);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * @Description 导出车辆
	 *  @param jsonData
	 */
	@RequestMapping("exportExcel.html")
	public void exportExcel(HttpServletResponse response,HttpServletRequest request,String data,String name){
		Enumeration<String> enumeration = request.getParameterNames();
		List<String> subRows = new ArrayList<String>();
		while (enumeration.hasMoreElements()) {
			String paramName = enumeration.nextElement();
			if (paramName.contains("subData")) {
				subRows.add(request.getParameter(paramName));
			}
		}
		data = StringUtils.join(subRows, "&");
		String[] rows = data.split("\\&");
		String[] titleArray = new String[9];
		titleArray[0] = "车牌号";
		titleArray[1] = "状态";
		titleArray[2] = "精度";
		titleArray[3] = "定位时间";
		titleArray[4] = "速度";
		titleArray[5] = "脉冲速度";
		titleArray[6] = "里程";
		titleArray[7] = "详细信息";
		titleArray[8] = "位置信息";
		List<Object>list = new ArrayList<Object>();
		for (int i = 0, size = rows.length; i < size; i++) {
			String track = rows[i];
			try {
				String[] trackArray = track.split("#");
				list.add(Arrays.asList(trackArray));
			} catch (Exception e) {
				logger.error("", e);
			}
		}
		exportExl(response, "订阅车辆信息", titleArray, list,null);
	}
	
	/**
	 * 导出列表数据到EXCEL表格
	 * @param fileName 导出的EXCEL表格文件名
	 * @param titleArray 表头标题数组
	 * @param dataList 列表数据
	 */
	@SuppressWarnings({ "deprecation", "rawtypes" })
	public void exportExl(HttpServletResponse response,String fileName, String[] titleArray,List dataList,int...args) {
		
		OutputStream outputStream = null;
		
		try {
			outputStream = response.getOutputStream();// 取得输出流
			response.reset();// 清空输出流
			response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8") + ".xls");// 设定输出文件头
			response.setContentType("application/msexcel");// 定义输出类型
			response.setCharacterEncoding("utf-8");
			
			HSSFWorkbook wb = new HSSFWorkbook();
			int page = (int) Math.ceil((double) dataList.size() / 65530);
			for (int k = 0; k < page; k++) {
				HSSFSheet sheet = wb.createSheet("Sheet" + k + 1);
				HSSFRow row = null;
				
				//生成标题
				row = sheet.createRow((short) 0);
				row.setHeight((short)500);
				row.createCell((short) 0).setCellValue("订阅车辆信息");
				HSSFCellStyle t0 = wb.createCellStyle(); 
				Font titleFont=wb.createFont();
				titleFont.setFontHeightInPoints((short) 15);
				titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
				t0.setFont(titleFont);
				t0.setAlignment(HSSFCellStyle.ALIGN_CENTER);
				row.getCell(0).setCellStyle(t0);
				CellRangeAddress cra = new CellRangeAddress(0, 0, 0,  titleArray.length-1);//起始行,结束行,起始列,结束列
				sheet.addMergedRegion(cra);
				
				if (titleArray != null) {
					row = sheet.createRow((short) 1);
					String signature="制表人："+ getSysUser().getLogin_name() + "          日期：" + DateUtil.getDateToString(new Date());
					row.createCell((short) 0).setCellValue(signature);
					row = sheet.createRow((short) 2);
					for (int i = 0; i < titleArray.length; i++) {
						row.createCell((short) i).setCellValue(new HSSFRichTextString(titleArray[i]));
						HSSFCellStyle t00 = wb.createCellStyle(); 
						Font titleFont0=wb.createFont();
						titleFont0.setFontHeightInPoints((short) 10);
						titleFont0.setBoldweight(Font.BOLDWEIGHT_BOLD);
						t00.setFont(titleFont0);
						t00.setAlignment(HSSFCellStyle.ALIGN_CENTER);
						row.getCell((short) i).setCellStyle(t00);
						int[] width = new int[]{60,50,50,150,50,80,80,400,400};;
						sheet.autoSizeColumn((short)0); //调整宽度
						sheet.setColumnWidth(i, (400/11)*width[i]);
					}
				}
				if (dataList != null) {
					List list = null;
					for (int m = 65530 * k; m < dataList.size(); m++) {
						row = sheet.createRow(m - 65530 * k + 3);
						list = (List) dataList.get(m);
						for (int n = 0; n < list.size(); n++) {
							row.createCell((short) n).setCellValue(new HSSFRichTextString(list.get(n) == null ? "" : list.get(n).toString()));
						}
						if (m == 65530 * (k + 3)) {
							break;
						}
					}
				}
			}
			wb.write(outputStream);
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					logger.error(e.getMessage(),e);
				}
			}
		}
		
	}
	
	/**
	 * @Description 获取当前司机信息
	 * @param vehicle_no_color 车牌号_车牌颜色
	 * @return
	 */
	@RequestMapping(value = "queryDriverInfo.html")
	public String queryDriverInfo(String vehicle_no_color,HttpServletResponse response){
		try {
			if(vehicle_no_color == null || "".equals(vehicle_no_color)){
				return null;
			}
			String no_color = URLDecoder.decode(vehicle_no_color, "utf-8");
			ObjDriver objDriver = monitorService.queryDriverInfo(no_color.split(","));
			this.ajaxResultJson(response, objDriver);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * @Description 获取当前部署地点的地址信息
	 * @return
	 */
	@RequestMapping(value = "queryDeploymentAreaInfo.jhtml")
	public void queryDeploymentAreaInfo(HttpServletResponse response){
		try {
			String platName = new String(config.plat_name.getBytes("ISO-8859-1"), "utf-8");
			Map<String, Object> info = new HashMap<>();
			if ("yicheng".equals(config.area_code)) {
				info.put("id", 0);
				info.put("code", "0");
				info.put("platName", platName);
				info.put("level", 1);
			}else {
				info = monitorService.queryDeploymentAreaInfo(config.area_code);
				info.put("platName", platName);
			}
			this.ajaxResultJson(response, info);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
